import { getUserFavoritePlaceListForPageForUser, getUserFavoriteListAllForUser } from '../../api/home'
import { imageURL } from '../../../utils/request'

Page({
  data: {
    tabs: [],
    days: [],
    user_favorite_id: '',
    showModal: false,
    activeIndex: 0,
    scrollLeft: 0,
    places: [],
    selectedDayIndex: 0,
    currentSelectedPlace: null,
    imageURL: '',
    isScrolling: false, // 是否正在滚动
  },
  // 滚动开始
  onDayPickerStart() {
    this.setData({
      isScrolling: true
    })
  },

  // 滚动结束
  onDayPickerEnd() {
    this.setData({
      isScrolling: false
    })
  },
  onLoad(e) {
    const days = Array.from({ length: e.diffDays }, (_, i) => `DAY ${i + 1}`)
    this.setData({ imageURL, days })
    this.getCollectType()
    this.getCollect()
  },
  onShow() {
    const payload = wx.getStorageSync('payload') || { list_item: [] };
    const selectedIds = payload.list_item.flatMap(d => d.child.map(c => c.place_id));
  
    if (this.data.places.length > 0) {
      const updatedPlaces = this.data.places.map(p => ({
        ...p,
        selected: selectedIds.includes(p.place_id)
      }));
      this.setData({ places: updatedPlaces });
    }
  },
  async getCollectType() {
    const res = await getUserFavoriteListAllForUser()
    const list = [{ name: '全部', user_favorite_id: '' }]
    this.setData({
      tabs: [...list, ...res.data.list]
    })
  },

  async getCollect() {
    const res = await getUserFavoritePlaceListForPageForUser({
      page: 1,
      rows: 9999,
      keyword: this.data.keyword,
      user_favorite_id: this.data.user_favorite_id
    })

    // 已勾选的 place_id
    const payload = wx.getStorageSync('payload') || { list_item: [] }
    const selectedIds = payload.list_item.flatMap(d => d.child.map(c => c.place_id))

    const list = (res.data.list || []).map(item => ({
      ...item,
      selected: selectedIds.includes(item.place_id)
    }))

    this.setData({ places: list })
  },

  // 搜索输入事件
  onInput(e) {
    this.setData({ keyword: e.detail.value })
    if (e.detail.value == '') {
      this.getCollect()
    }
  },
  back(){
    wx.navigateBack()
  },
  // 搜索确认事件
  onSearch() {
    this.getCollect()
  },

  // 点击切换Tab
  switchTab(e) {
    const index = e.currentTarget.dataset.index
    const user_favorite_id = e.currentTarget.dataset.user_favorite_id
    this.setData({
      activeIndex: index,
      user_favorite_id,
      scrollLeft: (index - 1) * 60
    })
    this.getCollect()
  },

  // picker 改变 DAY
  onDayPickerChange(e) {
    this.setData({ selectedDayIndex: e.detail.value[0] })
  },

  // 选择切换
  toggleSelect(e) {
    const id = e.currentTarget.dataset.id
    let showModal = false
    let currentSelectedPlace = null

    const places = this.data.places.map(p => {
      if (p.place_id === id) {
        const newSelected = !p.selected
        if (!p.selected && newSelected) {
          // 打开选择天数
          showModal = true
          currentSelectedPlace = p
        } else if (p.selected && !newSelected) {
          // 取消选择 -> 从 payload 删除
          this.removePlaceFromPayload(p.place_id)
        }
        return { ...p, selected: newSelected }
      }
      return p
    })

    this.setData({ places, showModal, currentSelectedPlace })
  },

  // 确认选择 -> 更新本地 payload
  confirmSelect() {
    if (this.data.isScrolling) {
      wx.showToast({
        title: '請等待滾動停止',
        icon: 'none'
      })
      return
    }
    const place = this.data.currentSelectedPlace
    const day_num = this.data.selectedDayIndex + 1

    if (!place) {
      wx.showToast({ title: '未選擇地點', icon: 'none' })
      return
    }

    let payload = wx.getStorageSync('payload') || {
      itinerary_id: '',
      itinerary_catalog_id: '',
      name: '',
      transportation: 1,
      start_time: '',
      end_time: '',
      img_url_cover: '',
      list_item: []
    }

    if (!payload.img_url_cover) {
      payload.img_url_cover = place.place_img_url_cover || ''
    }

    let dayItem = payload.list_item.find(d => d.day_num === day_num)
    if (!dayItem) {
      dayItem = { theme: '', day_num, child: [] }
      payload.list_item.push(dayItem)
    }

    const exists = dayItem.child.some(c => c.place_id === place.place_id)
    if (!exists) {
      dayItem.child.push({
        place_id: place.place_id,
        title: place.place_name,
        introduction: place.place_introduction,
        count_favorite:place.place_count_favorite,
        selected:true,
        type: 11,
        start_time: '',
        end_time: '',
        img_url_cover: place.place_img_url_cover || ''
      })
    }

    payload.list_item.sort((a, b) => a.day_num - b.day_num)

    wx.setStorageSync('payload', payload)

    this.setData({
      showModal: false,
      currentSelectedPlace: null,
      selectedDayIndex: 0
    })

    wx.showToast({ title: '已添加', icon: 'success' })
  },

  // 删除景点
  removePlaceFromPayload(place_id) {
    let payload = wx.getStorageSync('payload') || {}
    if (!payload.list_item) return

    payload.list_item.forEach(dayItem => {
      dayItem.child = dayItem.child.filter(c => c.place_id !== place_id)
    })
    payload.list_item = payload.list_item.filter(d => d.child.length > 0)

    wx.setStorageSync('payload', payload)
  }
})
